package com.inspur.edp.bef.bizentity.json.increment;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.inspur.edp.bef.bizentity.common.BizEntityJsonConst;
import com.inspur.edp.bef.bizentity.exceptions.BusinessEntityErrorCodeEnum;
import com.inspur.edp.bef.bizentity.exceptions.BusinessEntityException;
import com.inspur.edp.bef.bizentity.increment.entity.determination.AddedDtmIncrement;
import com.inspur.edp.bef.bizentity.increment.entity.determination.DtmIncrement;
import com.inspur.edp.bef.bizentity.json.operation.BizDeterminationSerializer;
import com.inspur.edp.bef.bizentity.operation.Determination;
import com.inspur.edp.cef.designtime.api.json.CefNames;
import com.inspur.edp.cef.designtime.api.json.SerializerUtils;

import java.io.IOException;

public class DtmIncrementSerializer extends JsonSerializer<DtmIncrement> {

    @Override
    public void serialize(DtmIncrement value, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {
        SerializerUtils.writeStartObject(gen);
        writeBaseInfo(value, gen);
        SerializerUtils.writeEndObject(gen);
    }

    private void writeBaseInfo(DtmIncrement value, JsonGenerator gen) {
        SerializerUtils.writePropertyValue(gen, CefNames.IncrementType, value.getIncrementType().toString());
        switch (value.getIncrementType()) {
            case Added:
                writeAddedIncrement((AddedDtmIncrement) value, gen);
                break;
            case Modify:
//                writeModifyIncrement((ModifyMgrActionIncrement) value, gen);
                break;
            case Deleted:
//                writeDeletedIncrement((DeletedEntityIncrement) value, gen);
                break;
            default:
                throw BusinessEntityException.createException(BusinessEntityErrorCodeEnum.GSP_BEMODEL_ENUM_NOTSUPPORT_0004, value.getIncrementType().toString());
        }
    }

    private void writeAddedIncrement(AddedDtmIncrement increment, JsonGenerator gen) {
        SerializerUtils.writePropertyName(gen, BizEntityJsonConst.AddedAction);
        writeBaseActionInfo(increment.getAction(), gen);
    }

    private void writeBaseActionInfo(Determination action, JsonGenerator gen) {
        BizDeterminationSerializer convertor = new BizDeterminationSerializer();
        try{
            convertor.serialize(action, gen, null);
        }catch (Exception e){
            throw BusinessEntityException.createException(BusinessEntityErrorCodeEnum.GSP_BEMODEL_JSON_0004, e, "Determination", action.getCode());
        }
    }
}
